package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.DbManager;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import zj.com.adapter.FragmentAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.fragments.GrzxFragment;
import zj.com.fragments.JcdInfoFragment;
import zj.com.fragments.JcxFragment;
import zj.com.model.Dic;
import zj.com.model.InspectContent;
import zj.com.model.InspectItem;
import zj.com.model.JcdInfoDB;
import zj.com.model.JcxDB;
import zj.com.model.JcxDetailDB;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/3.
 * 检查单编辑页面
 */
public class JcdEditActivity extends FragmentActivity implements View.OnClickListener{


    public TextView title_name;
    public ImageView left_iv;
    public TextView right_tv;

    private List<Fragment> mFragmentList = new ArrayList<Fragment>();
    private FragmentAdapter mFragmentAdapter;
    private int screenWidth;
    private ViewPager mPageVp;
    /**
     * Tab显示内容TextView
     */
    private TextView mjcxTv, mjcdTv;
    /**
     * Tab的那个引导线
     */
    private ImageView mTabLineIv;

    private  Fragment jcdInfoFragment,jcxFragment;
    private int currentIndex;
    public int  mode;

    public LinearLayout id_tab_friend_ll,id_tab_chat_ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jcd_edit);
        initView();
        init();
        initTabLineWidth();
    }





    public void initView(){

        id_tab_chat_ll = (LinearLayout) findViewById(R.id.id_tab_chat_ll);
        id_tab_chat_ll.setOnClickListener(this);
        id_tab_friend_ll = (LinearLayout) findViewById(R.id.id_tab_friend_ll);
        id_tab_friend_ll.setOnClickListener(this);

        title_name = (TextView) findViewById(R.id.title_name);
         mode = getIntent().getIntExtra("mode",0);
        if(mode == 1){
            title_name.setText("创建检查单");

        }else{
            title_name.setText("修改检查单");

        }

        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setOnClickListener(this);
        left_iv.setVisibility(View.VISIBLE);
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setText("保存");
        right_tv.setOnClickListener(this);

        mjcdTv = (TextView) this.findViewById(R.id.id_jcd_tv);
        mjcxTv = (TextView) this.findViewById(R.id.id_jcx_tv);

        mTabLineIv = (ImageView) this.findViewById(R.id.id_tab_line_iv);

        mPageVp = (ViewPager) this.findViewById(R.id.id_page_vp);
    }

    private void init() {
        jcdInfoFragment = new JcdInfoFragment();
        JcdInfoFragment.isDqr = false;
        jcxFragment = new JcxFragment();
        mFragmentList.add(jcdInfoFragment);
        mFragmentList.add(jcxFragment);

        mFragmentAdapter = new FragmentAdapter(
                this.getSupportFragmentManager(), mFragmentList);
        mPageVp.setAdapter(mFragmentAdapter);
        mPageVp.setCurrentItem(0);

        mPageVp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            /**
             * state滑动中的状态 有三种状态（0，1，2） 1：正在滑动 2：滑动完毕 0：什么都没做。
             */
            @Override
            public void onPageScrollStateChanged(int state) {

            }

            /**
             * position :当前页面，及你点击滑动的页面 offset:当前页面偏移的百分比
             * offsetPixels:当前页面偏移的像素位置
             */
            @Override
            public void onPageScrolled(int position, float offset,
                                       int offsetPixels) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
                        .getLayoutParams();

                Log.e("wxf", "postion=" + position + "    offset=" + offset + " =====currentIndex=" + currentIndex);

                if (currentIndex == 0 && position == 0)// 0->1
                {
//                    lp.leftMargin = (int) (offset * (screenWidth * 1.0) + currentIndex
//                            * (screenWidth / 2));
                    lp.leftMargin =
                             0;
                    Log.e("wxf","0  0");


                }else if(currentIndex ==1 && position ==0){
                    Log.e("wxf","1  0");
                    lp.leftMargin =
                             screenWidth / 2;
                }else if(currentIndex ==1 && position ==1){

                    Log.e("wxf","1  1");
                    lp.leftMargin =
                            screenWidth / 2;
                }
              // mTabLineIv.setLayoutParams(lp);
            }

            @Override
            public void onPageSelected(int position) {
                resetTextView();
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
                        .getLayoutParams();
                switch (position) {
                    case 0:
                        mjcdTv.setTextColor(getResources().getColor(R.color.color_text_p));

                        lp.leftMargin =0;
                        break;
                    case 1:


                        lp.leftMargin =
                                screenWidth / 2;
                        mjcxTv.setTextColor(getResources().getColor(R.color.color_text_p));
                             ;
                        break;

                }
                mTabLineIv.setLayoutParams(lp);
                currentIndex = position;
            }
        });

    }

    /**
     * 设置滑动条的宽度为屏幕的1/3(根据Tab的个数而定)
     */
    private void initTabLineWidth() {
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(dpMetrics);
        screenWidth = dpMetrics.widthPixels;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
                .getLayoutParams();
        lp.width = screenWidth / 2;
        mTabLineIv.setLayoutParams(lp);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        jcdInfoFragment.onActivityResult(requestCode,resultCode,data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 重置颜色
     */
    private void resetTextView() {
        mjcxTv.setTextColor(Color.parseColor("#828282"));
        mjcdTv.setTextColor(Color.parseColor("#828282"));
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.right_tv:
                saveData();
                break;
            case R.id.id_tab_friend_ll:
                mPageVp.setCurrentItem(1);
                break;
            case R.id.id_tab_chat_ll:
                mPageVp.setCurrentItem(0);

                break;

        }
    }

    public void saveData(){

     JcdInfoDB jcdInfo =  ZjApplication.jcd;
     if(jcdInfo != null){

         if(jcdInfo.getInspectType() == -1 ){

             Toast.makeText(this,"请选择检查单类型",Toast.LENGTH_SHORT).show();
             return;
         }
         if(jcdInfo.getInspectDate() == null){
             Toast.makeText(this,"请选择检查日期",Toast.LENGTH_SHORT).show();
             return;
         }
         if(jcdInfo.getInspectOrgCode() == null || jcdInfo.getInspectProjectCode() == null){

             Toast.makeText(this,"请选择检查公司或者检查项目",Toast.LENGTH_SHORT).show();
             return;
         }

         List<InspectItem> items = ZjApplication.inspectItems;
         try{

             DbManager dbManager =  DBUtil.getInstance(this).getDBManager();

         if(items == null || items.size() == 0){

         }else{
             List<InspectItem> itemList = ZjApplication.inspectItems;
             List<JcxDB> jcxList = new ArrayList<JcxDB>();
             for(InspectItem item :itemList){

                 JcxDB jcx =new JcxDB();

                 if(item.getId() == null){
                     jcx.setId(UUID.randomUUID().toString());
                 }else{
                     jcx.setId(item.getId());
                 }
                 jcx.setInspectionNo(jcdInfo.getInspectionNo());
                 jcx.setInspectType(item.getInspectType());
                 jcx.setRiskName(item.getRiskName());
                 jcx.setInspectItemName(item.getInspectItemName());
                 jcx.setInspectItemCode(item.getInspectItemCode());
                 jcx.setTaskName(item.getTaskName());
                 jcx.setEndDate(item.getEndDate());
                 jcx.setSpecialtyCode(item.getSpecialtyCode());
                 String zyName = item.getZyName();
                 jcx.setZyName(zyName);

                 List<InspectContent> contents =  item.getContents();
                 if(contents == null || contents.size() == 0){
                     contents =DBUtil.getInstance(this).getDBManager().selector(InspectContent.class).where("inspectitemid", "=", item.getInspectItemID()).findAll();

                     LogUtils.getInstance().error("==================contents  is nulllllllll=================");
                 }else{
                     LogUtils.getInstance().error("==================contents  =================");

                 }
                 List<JcxDetailDB> details =new ArrayList<>();
                 for(InspectContent content:contents){

                     LogUtils.getInstance().error(" "+content.getDes()+","+content.getImgs()+","+content.getPoints());
                     JcxDetailDB jd = new JcxDetailDB();
                     jd.setInspectItemCode(item.getInspectItemCode());
                     jd.setInspectionno(jcdInfo.getInspectionNo());
                     if(content.getId() == null){
                         jd.setId(UUID.randomUUID().toString());
                     }else{
                         jd.setId(content.getId());
                     }
                     if(content.getPoints() != 0){
                         jd.setContent(content.getDes());
                         jd.setContentId(content.getInspectContentID());
                         jd.setInspectContentName(content.getInspectContentName());
                         jd.setPoints(content.getPoints());
                         jd.setDesc(content.getDes());
                         Dic dic = content.getDic();
                         if(dic != null){
                             jd.setRiskLevel(content.getDic().getValue());
                             jd.setRiskName(content.getDic().getName());
                         }
                         jd.setMaxPoints(content.getMaxPoints());
                         List<String> imgs = content.getImgs();
                         LogUtils.getInstance().error("==save=imgs==="+imgs+"   "+ imgs.size());
                         StringBuffer sb = new StringBuffer();
                         for (String s:imgs){
                             LogUtils.getInstance().error("===s==="+s);
                             if(!TextUtils.isEmpty(s)){
                                 LogUtils.getInstance().error("===s2==="+s);

                                 sb.append(s);
                                 sb.append(",");
                             }

                         }
                         jd.setImgs(sb.toString());

//                         if(content.getDes() != "" && !TextUtils.isEmpty(sb.toString()) && imgs.size()> 0 && dic != null){
//                             jcdInfo.setIsOk("1");
//                         }

                     }else{
                         jd.setContentId(content.getInspectContentID());
                         jd.setInspectContentName(content.getInspectContentName());
                         jd.setContent(content.getDes());
                         jd.setDesc(content.getDes());
                         jd.setMaxPoints(content.getMaxPoints());
                         jd.setPoints(0);
                         Dic dic = content.getDic();
                         if(dic != null){
                             jd.setRiskLevel(content.getDic().getValue());
                             jd.setRiskName(content.getDic().getName());
                         }
                         List<String> imgs = content.getImgs();
                         if(imgs != null){
                             StringBuffer sb = new StringBuffer();
                             for (String s:imgs){
                                 sb.append(s);
                                 sb.append(",");
                             }
                             jd.setImgs(sb.toString());
                         }


                     }

                     jd.setRiskType(content.getRiskType());
                     jd.setRiskTypeName(content.getRiskTypeName());
                     details.add(jd);


                 }
                 jcxList.add(jcx);
                 dbManager.saveOrUpdate(details);

             }
             dbManager.saveOrUpdate(jcxList);




         }

             List<JcxDetailDB> details =   DBUtil.getInstance(this).getDBManager().selector(JcxDetailDB.class).where("inspectionno", "=", jcdInfo.getInspectionNo()).and("imgs","!=","").and("desc","!=","").and("points",">","0").findAll();
             if(details != null && details.size() > 0){


                 jcdInfo.setIsOk("1");
             }else{
                 jcdInfo.setIsOk("0");
             }


             dbManager.saveOrUpdate(jcdInfo);
             ZjApplication.isUpdateJcd = false;
             ZjApplication.jcd = null;
             ZjApplication.pgScan = null;
             ZjApplication.inspectItems.clear();
             Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
             finish();

         }catch(Exception e){
             LogUtils.getInstance().error(e.toString());
             //Toast.makeText(this, "保存失败!", Toast.LENGTH_SHORT).show();

         }



     }

    }



}
